<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" th:replace="~{layout/base :: layout(~{::title}, ~{::content}, ~{::css}, ~{::js})}">
<head>
    <title>分类管理 - 笔记管理系统</title>
    <th:block th:fragment="css">
        <style>
            .category-container {
                background: white;
                border-radius: 10px;
                padding: 30px;
                box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            }
            .category-item {
                background: #f8f9fa;
                border: 1px solid #e9ecef;
                border-radius: 8px;
                padding: 20px;
                margin-bottom: 15px;
                transition: all 0.3s;
            }
            .category-item:hover {
                transform: translateY(-2px);
                box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            }
            .category-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-bottom: 10px;
            }
            .category-name {
                font-size: 1.2rem;
                font-weight: 600;
                color: #333;
            }
            .category-count {
                background: #007bff;
                color: white;
                padding: 4px 12px;
                border-radius: 15px;
                font-size: 0.875rem;
            }
            .category-description {
                color: #666;
                margin-bottom: 15px;
                line-height: 1.5;
            }
            .category-actions {
                display: flex;
                gap: 10px;
            }
            .btn-sm {
                padding: 5px 12px;
                font-size: 0.875rem;
            }
            .empty-state {
                text-align: center;
                padding: 60px 20px;
                color: #666;
            }
            .empty-state i {
                font-size: 4rem;
                color: #ddd;
                margin-bottom: 20px;
            }
            .modal-body .form-group {
                margin-bottom: 20px;
            }
        </style>
    </th:block>
</head>
<body>
    <div th:fragment="content">
        <!-- 页面标题 -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2>
                <i class="fas fa-folder me-2"></i>分类管理
            </h2>
            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#categoryModal" onclick="openAddModal()">
                <i class="fas fa-plus me-2"></i>新建分类
            </button>
        </div>

        <!-- 分类列表 -->
        <div class="category-container">
            <div id="categoryList">
                <!-- 分类项将通过AJAX加载 -->
            </div>
        </div>

        <!-- 分类编辑模态框 -->
        <div class="modal fade" id="categoryModal" tabindex="-1">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="modalTitle">新建分类</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <form id="categoryForm">
                            <input type="hidden" id="categoryId" name="id">
                            <div class="form-group">
                                <label for="categoryName" class="form-label">分类名称 <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="categoryName" name="categoryName" required>
                                <div class="form-text">分类名称必须唯一</div>
                            </div>
                            <div class="form-group">
                                <label for="description" class="form-label">描述</label>
                                <textarea class="form-control" id="description" name="description" rows="3" placeholder="请输入分类描述"></textarea>
                            </div>
                            <div class="form-group">
                                <label for="sortOrder" class="form-label">排序</label>
                                <input type="number" class="form-control" id="sortOrder" name="sortOrder" value="0" min="0">
                                <div class="form-text">数字越小排序越靠前</div>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" onclick="saveCategory()">保存</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <th:block th:fragment="js">
        <script>
            $(document).ready(function() {
                loadCategories();
            });

            // 加载分类列表
            function loadCategories() {
                $.get('/note/category/listWithCount', function(data) {
                    if (data.code === 200) {
                        renderCategories(data.data);
                    } else {
                        showError('加载分类列表失败：' + data.msg);
                    }
                });
            }

            // 渲染分类列表
            function renderCategories(categories) {
                let html = '';
                
                if (categories.length === 0) {
                    html = `
                        <div class="empty-state">
                            <i class="fas fa-folder-open"></i>
                            <h4>暂无分类</h4>
                            <p>还没有创建任何分类，<a href="#" onclick="openAddModal()" data-bs-toggle="modal" data-bs-target="#categoryModal">立即创建</a>第一个分类吧！</p>
                        </div>
                    `;
                } else {
                    categories.forEach(function(category) {
                        html += `
                            <div class="category-item">
                                <div class="category-header">
                                    <div class="category-name">${category.categoryName}</div>
                                    <div class="category-count">${category.noteCount || 0} 篇笔记</div>
                                </div>
                                <div class="category-description">
                                    ${category.description || '暂无描述'}
                                </div>
                                <div class="category-actions">
                                    <button class="btn btn-outline-primary btn-sm" onclick="editCategory(${category.id})" data-bs-toggle="modal" data-bs-target="#categoryModal">
                                        <i class="fas fa-edit me-1"></i>编辑
                                    </button>
                                    <a href="/note?categoryId=${category.id}" class="btn btn-outline-info btn-sm">
                                        <i class="fas fa-eye me-1"></i>查看笔记
                                    </a>
                                    <button class="btn btn-outline-danger btn-sm" onclick="deleteCategory(${category.id}, '${category.categoryName}', ${category.noteCount || 0})">
                                        <i class="fas fa-trash me-1"></i>删除
                                    </button>
                                </div>
                            </div>
                        `;
                    });
                }
                
                $('#categoryList').html(html);
            }

            // 打开新建模态框
            function openAddModal() {
                $('#modalTitle').text('新建分类');
                $('#categoryForm')[0].reset();
                $('#categoryId').val('');
            }

            // 编辑分类
            function editCategory(id) {
                $('#modalTitle').text('编辑分类');
                
                $.get(`/note/category/selectById?id=${id}`, function(data) {
                    if (data.code === 200) {
                        let category = data.data;
                        $('#categoryId').val(category.id);
                        $('#categoryName').val(category.categoryName);
                        $('#description').val(category.description);
                        $('#sortOrder').val(category.sortOrder || 0);
                    } else {
                        showError('加载分类信息失败：' + data.msg);
                    }
                });
            }

            // 保存分类
            function saveCategory() {
                // 验证必填字段
                if (!$('#categoryName').val().trim()) {
                    showError('请输入分类名称');
                    return;
                }

                // 构建JSON数据
                let formData = {
                    categoryName: $('#categoryName').val().trim(),
                    description: $('#description').val(),
                    sortOrder: parseInt($('#sortOrder').val()) || 0
                };
                
                // 如果是编辑，添加ID字段
                let categoryId = $('#categoryId').val();
                let url = '/note/category/add';
                if (categoryId) {
                    formData.id = categoryId;
                    url = '/note/category/edit';
                }

                // 检查名称是否重复
                let categoryName = $('#categoryName').val().trim();
                
                $.get('/note/category/checkUnique', {
                    categoryName: categoryName
                }, function(data) {
                    if (data.code !== 200) {
                        showError('分类名称已存在，请使用其他名称');
                        return;
                    }
                    
                    // 名称唯一，保存分类
                    $.ajax({
                        url: url,
                        type: 'POST',
                        contentType: 'application/json',
                        data: JSON.stringify(formData),
                        success: function(data) {
                            if (data.code === 200) {
                                showSuccess('保存成功');
                                $('#categoryModal').modal('hide');
                                loadCategories();
                            } else {
                                showError('保存失败：' + data.msg);
                            }
                        },
                        error: function(xhr, status, error) {
                            showError('保存失败：' + error);
                        }
                    });
                });
            }

            // 删除分类
            function deleteCategory(id, name, noteCount) {
                if (noteCount > 0) {
                    showError(`分类"${name}"下还有${noteCount}篇笔记，无法删除。请先删除或移动这些笔记。`);
                    return;
                }
                
                if (confirm(`确定要删除分类"${name}"吗？`)) {
                    $.post('/note/category/remove', {ids: id}, function(data) {
                        if (data.code === 200) {
                            showSuccess('删除成功');
                            loadCategories();
                        } else {
                            showError('删除失败：' + data.msg);
                        }
                    });
                }
            }

            // 表单提交处理
            $('#categoryForm').on('submit', function(e) {
                e.preventDefault();
                saveCategory();
            });

            // 模态框关闭时重置表单
            $('#categoryModal').on('hidden.bs.modal', function() {
                $('#categoryForm')[0].reset();
                $('#categoryId').val('');
            });

            // 显示成功消息
            function showSuccess(message) {
                alert(message); // 简单实现，可以替换为更好的提示组件
            }

            // 显示错误消息
            function showError(message) {
                alert(message); // 简单实现，可以替换为更好的提示组件
            }
        </script>
    </th:block>
</body>
</html>